package kubernetes

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"k8s-admin/dao/kubernetes"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
	"time"
)

func (c *k8sCluster) AddK8sCluster(cluster *models.Configs) (err error) {
	// 根据时间戳生成cid
	localTime := time.Now().String()
	sum := md5.Sum([]byte(localTime))
	cluster.CID = hex.EncodeToString(sum[:])
	decodeConfig, _ := utils.DecodeBase64(cluster.Text)
	fmt.Println(decodeConfig)
	/*
		这里初始化客户端是因为，数据库中的version字段需要k8s的版本号
	*/
	clientSet, err := global.NewClientInterface().NewClientSet(decodeConfig) // 生成客户端
	if err != nil {
		fmt.Println("生成客户端错误: ", err)
		return err
	}
	version, _ := clientSet.ServerVersion() // 查看k8s版本
	cluster.Version = version.String()
	err = kubernetes.NewK8sCluster().AddK8sCluster(cluster) // 把集群信息添加到数据库中
	if err != nil {
		global.TPLogger.Error(err)
		return err
	} else {
		return nil
	}
}

func (c *k8sCluster) ListK8sCluster(Limit, Page int) (*models.ClusterK8sList, error) {
	cluster, err := kubernetes.NewK8sCluster().ListK8sCluster(Limit, Page)
	if err != nil {
		return nil, err
	} else {
		return cluster, nil
	}
}

func (c *k8sCluster) DeleteK8sCluster(cid []string) error {
	err := kubernetes.NewK8sCluster().DeleteK8sCluster(cid)
	if err != nil {
		global.TPLogger.Error(err)
		return err
	} else {
		return nil
	}
}
